import Loading from "@/components/Loading/index.vue";
import { createApp } from "vue";

export const DemoInstruct = (app: any) => {
  app.directive("demo", {
    mounted(el: any, options: any) {},

    updated(el: any, options: any) {
      const { value } = options;
      const loadingDom = createDiv(el);
      // 当指令为true时
      if (value) {
        mountDiv(el, loadingDom);
      } else {
        removeDiv(el);
      }
    },
  });
};

/**
 * 创建
 */
function createDiv(el: any) {
  const loadingDom = document.createElement("div");
  el.style.position = "relative";
  loadingDom.style.width = `${el.offsetWidth}px`;
  loadingDom.style.height = `${el.offsetHeight}px`;
  loadingDom.style.maxHeight = "100vh";
  loadingDom.style.position = `absolute`;
  loadingDom.style.background = `#fff`;
  loadingDom.style.display = `flex`;
  loadingDom.style.justifyContent = `center`;
  loadingDom.style.alignItems = `center`;
  loadingDom.style.top = "0";
  loadingDom.style.borderRadius = "inherit";

  return loadingDom;
}

/**
 * 挂载
 */
function mountDiv(el: any, dom: any) {
  const app = createApp(Loading);
  const instance = app.mount(dom);
  dom.appendChild(instance.$el);
  el.appendChild(dom);
}

/**
 * 移除
 */
function removeDiv(el: any) {
  el.removeChild(el.lastChild);
  return;
}
